import fly from '@/utils/fly'
import store from '@/store'
import { api } from '@/api/login'

export function wxlogin() {
  wx.login({
    success: function(res) {
      fly
        .post('/api/aierp/v1/user/wxLogin', { code: res.code })
        .then(function(res) {
          if (res.data.wxStatus == true) {
            //获取openid
            var openid = res.data.openid

            api.login({username:openid,loginType:'wxWorker'}).then(res => {
              wx.setStorageSync('sessionToken', res.data)
              wx.setStorageSync('isLogin', true)
              store.commit('SET_TOKEN', res.data)
              store.commit('SET_ISLOGIN', true)

              //登录成功将用户信息设置store里
              store.dispatch('GetWorkerInfo').then(res => {
                wx.setStorageSync('userInfo', res.data)
                store.commit('SET_USER_INFO', res.data)
              })
              
              

            })

            wx.showLoading({
              title: '登陆成功...'
            })
            setTimeout(function() {
              wx.reLaunch({ url: '../index/index' })
              wx.hideLoading()
            }, 300)
          } else {
            wx.showModal({
              title: '登陆提醒',
              content: '请先注册',
              success: function(res) {
                if (res.confirm) {
                  wx.showLoading({
                    title: '加载中'
                  })
                  setTimeout(function() {
                    wx.reLaunch({ url: '../regist/index' })
                    wx.hideLoading()
                  }, 300)
                } else if (res.cancel) {
                  //getUserInfo();
                }
              }
            })
          }
        })
    }
  })
}
